package com.xjrsoft.module.visual.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjrsoft.common.core.VoToColumn;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.result.Response;
import com.xjrsoft.core.tool.utils.AesUtil;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.visual.dto.*;
import com.xjrsoft.module.visual.entity.*;
import com.xjrsoft.module.visual.service.*;
import com.xjrsoft.module.visual.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 可视化表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-12-19
 */
@RestController
@RequestMapping("/visual")
@Api(value = "/visual",tags = "BI看板大屏模块")
@AllArgsConstructor
public class XjrVisualController {

    @Autowired
    private final IXjrVisualConfigService visualConfigService;

    @Autowired
    private final IXjrVisualCategoryService visualCategoryService;

    @Autowired
    private final IXjrVisualMapService visualMapService;

    @Autowired
    private final IXjrVisualService visualService;

    @Autowired
    private final IXjrVisualDbService visualDbService;

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[dto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:查询分页
     */
    @GetMapping("/list")
    @ApiOperation("查询分页")
    public Response getPageList(VisualListDto dto) {
        return Response.ok(visualService.selectPageData(dto));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id]
     * @return:com.xjrsoft.common.result.Response
     * @Description: 根据id查询模板详情
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("根据id查询模板详情")
    public Response getById(@PathVariable String id) {
        JSONObject result = new JSONObject();
        VisualVo visualVo = BeanUtil.copy(visualService.getById(id), VisualVo.class);
        XjrVisualConfig visualConfig = visualConfigService.getByVisualId(id);
        result.put("config", visualConfig);
        result.put("visual", visualVo);
        return Response.ok(result);
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:新增
     */
    @PostMapping
    @ApiOperation("新增")
    @SneakyThrows
    public Response save(@RequestBody SaveVisualDto dto) {
        return Response.ok(visualService.saveVisual(dto));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:更新
     */
    @PutMapping("/{id}/detail")
    @ApiOperation("更新")
    public Response updateDetail(@PathVariable String id, @RequestBody SaveVisualDto dto) {
        XjrVisual visual = BeanUtil.copy(dto.getVisual(), XjrVisual.class);
        XjrVisualConfig visualConfig = BeanUtil.copy(dto.getConfig(), XjrVisualConfig.class);
        return Response.ok(visualService.updateVisualDetail(id, visual, visualConfig));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:更新
     */
    @PutMapping("/{id}")
    @ApiOperation("更新")
    public Response updateVisual(@PathVariable String id, @RequestBody SaveVisualDto dto) {
        XjrVisual visual = BeanUtil.copy(dto.getVisual(), XjrVisual.class);
        visual.setId(id);

        if(dto.getConfig() != null){
            XjrVisualConfig config = BeanUtil.copy(dto.getConfig(),XjrVisualConfig.class);
            visualConfigService.updateById(config);
        }


        return Response.ok(visualService.updateById(visual));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id, kbInfoDto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:拷贝
     */
    @PostMapping("/{id}/copy")
    @ApiOperation("拷贝")
    public Response copy(@PathVariable("id") String id,String categroy) {
        XjrVisual visual = visualService.getById(id);
        String newVisualId = IdWorker.get32UUID();
        if(StringUtil.isNotBlank(categroy)){
            visual.setCategory(categroy);
        }
        visual.setId(newVisualId);
        XjrVisualConfig visualConfig = visualConfigService.getByVisualId(id);
        visualConfig.setId(IdWorker.get32UUID());
        visualConfig.setVisualId(newVisualId);
        visualService.save(visual);
        visualConfigService.save(visualConfig);
        return Response.ok(newVisualId);
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:删除看板信息
     */
    @DeleteMapping("/{ids}")
    @ApiOperation("删除看板信息")
    public Response delete(@PathVariable String ids) {
        return Response.status(visualService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:查询BI分类
     */
    @GetMapping("/category/list")
    @ApiOperation("查询BI分类")
    public Response listCategory() {
        return Response.ok(visualCategoryService.list());
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:查询分类详情
     */
    @GetMapping("/category/detail/{categoryId}")
    @ApiOperation("查询分类详情")
    public Response getCategoryDetail(@PathVariable("categoryId") String id) {
        return Response.ok(visualCategoryService.getById(id));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[dto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:新增分类
     */
    @PostMapping("/category")
    @ApiOperation("新增分类")
    public Response saveCategory(@RequestBody VisualCategoryDto dto) {
        XjrVisualCategory visualCategory = BeanUtil.copy(dto, XjrVisualCategory.class);
        visualCategory.setId(IdWorker.get32UUID());
        visualCategory.setIsDeleted(0);
        return Response.status(visualCategoryService.save(visualCategory));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id, dto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:更新分类
     */
    @PutMapping("/category/{categoryId}")
    @ApiOperation("更新分类")
    public Response updateCategory(@PathVariable("categoryId") String id, @RequestBody VisualCategoryDto dto) {
        XjrVisualCategory visualCategory = BeanUtil.copy(dto, XjrVisualCategory.class);
        visualCategory.setId(id);
        return Response.status(visualCategoryService.updateById(visualCategory));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id]
     * @return:com.xjrsoft.common.result.Response
     * @Description:删除分类
     */
    @DeleteMapping("/category/{categoryId}")
    @ApiOperation("删除分类")
    public Response deleteCategory(@PathVariable("categoryId") String id) {
        return Response.status(visualCategoryService.removeById(id));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[]
     * @return:com.xjrsoft.common.result.Response
     * @Description:查询地图数据分页
     */
    @GetMapping("/map/list")
    @ApiOperation("查询地图数据分页")
    public Response listMap(GetListVisualMapDto dto) {

        QueryWrapper<XjrVisualMap> query = new QueryWrapper<>();
        query.select(XjrVisualMap.class, x -> VoToColumn.Convert(VisualMapListVo.class).contains(x.getColumn()));
        IPage<XjrVisualMap> page = visualMapService.page(ConventPage.getPage(dto), query);
        PageOutput<VisualMapListVo> pageOutput = ConventPage.getPageOutput(page, VisualMapListVo.class);
        return Response.ok(pageOutput);
    }

//    /**
//     * @Author:湘北智造-框架开发组
//     * @Date:2020/12/19
//     * @Param:[]
//     * @return:com.xjrsoft.common.result.Response
//     * @Description:查询地图详情
//     */
//    @GetMapping("/map/detail/{mapId}")
//    @ApiOperation("查询地图详情")
//    public String getMapDetail(@PathVariable("mapId") String id) {
//        XjrVisualMap map = visualMapService.getById(id);
//        return map.getData();
//    }

    @GetMapping("/map/detail/{mapId}")
    @ApiOperation("查询地图详情, 编辑地图查看详情时使用")
    public Response getMapDetailToUpdate(@PathVariable("mapId") String id) {
        XjrVisualMap map = visualMapService.getById(id);
        VisualMapVo mapVo = BeanUtil.copy(map, VisualMapVo.class);
        return Response.ok(mapVo);
    }

    @GetMapping("/map/data")
    @ApiOperation("查询地图详情, 编辑地图查看详情时使用")
    public Object getMapData(@RequestParam("id") String id) {
        XjrVisualMap map = visualMapService.getById(id);

        return map == null ? null : JSONObject.parseObject(map.getData());
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[dto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:新增地图
     */
    @PostMapping("/map")
    @ApiOperation("新增地图")
    public Response saveMap(@RequestBody VisualMapDto dto) {
        XjrVisualMap visualMap = BeanUtil.copy(dto, XjrVisualMap.class);
        visualMap.setId(IdWorker.get32UUID());
        return Response.status(visualMapService.save(visualMap));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id, dto]
     * @return:com.xjrsoft.common.result.Response
     * @Description:更新地图
     */
    @PutMapping("/map/{mapId}")
    @ApiOperation("更新地图")
    public Response updateMap(@PathVariable("mapId") String id, @RequestBody VisualMapDto dto) {
        XjrVisualMap visualMap = BeanUtil.copy(dto, XjrVisualMap.class);
        visualMap.setId(id);
        return Response.status(visualMapService.updateById(visualMap));
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/12/19
     * @Param:[id]
     * @return:com.xjrsoft.common.result.Response
     * @Description:删除分类
     */
    @DeleteMapping("/map/{mapId}")
    @ApiOperation("删除分类")
    public Response deleteMap(@PathVariable("mapId") String id) {
        return Response.status(visualMapService.removeById(id));
    }


    /**
     * @Author:湘北智造-框架开发组
     * @Date:2021/12/15
     * @Param:[id]
     * @return:com.xjrsoft.common.result.Response
     * @Description:获取数据源详情
     */
    @GetMapping("/db/{dbId}/detail")
    @ApiOperation("获取数据源详情")
    public Response getDbDetail(@PathVariable("dbId") String id) {
        XjrVisualDb visualDb = visualDbService.getById(id);
        VisualDbDetailVo vo = BeanUtil.copy(visualDb,VisualDbDetailVo.class);
        return Response.ok(vo);
    }

    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: dto
     * @return: com.xjrsoft.common.result.Response
     * @Description: 获取数据源分页列表
     */
    @GetMapping("/db/list")
    @ApiOperation("获取数据源分页列表")
    public Response getDbList(VisualDbDto dto) {
        return Response.ok(ConventPage.getPageOutput(visualDbService.page(ConventPage.getPage(dto)), VisualDbVo.class));
    }


    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: dto
     * @return: com.xjrsoft.common.result.Response
     * @Description: 新增数据源
     */
    @PostMapping("/db/add")
    @ApiOperation("新增数据源")
    public Response addDb(@RequestBody SaveVisualDbVo dto) {
        XjrVisualDb visualDb = BeanUtil.copy(dto, XjrVisualDb.class);
        visualDb.setStatus(1);
        visualDb.setIsDeleted(0);
        return Response.ok(visualDbService.save(visualDb));
    }

    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: dto
     * @return: com.xjrsoft.common.result.Response
     * @Description: 修改数据源
     */
    @PutMapping("/db/{dbId}")
    @ApiOperation("修改数据源")
    public Response<Boolean> updateDb(@PathVariable("dbId") String id,@RequestBody SaveVisualDbVo dto) {
        XjrVisualDb visualDb = BeanUtil.copy(dto, XjrVisualDb.class);
        visualDb.setId(id);
        return Response.status(visualDbService.updateById(visualDb));
    }

    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: id
     * @return: com.xjrsoft.common.result.Response
     * @Description: 修改数据源
     */
    @DeleteMapping("/db/{dbId}")
    @ApiOperation("删除")
    public Response<Boolean> deleteDb(@PathVariable("dbId") String ids) {
        List<String> idsArry = Arrays.asList(ids.split(","));
        return Response.status(visualDbService.removeByIds(idsArry));
    }


    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: dto
     * @return: com.xjrsoft.common.result.Response
     * @Description: 测试数据源
     */
    @PostMapping("/db/db-test")
    @ApiOperation("测试数据源")
    public Response<Boolean> testDb(@RequestBody TestDbDto dto) throws SQLException, ClassNotFoundException {
        return Response.status(visualDbService.testConnectionDb(dto));
    }

    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: id
     * @return: com.xjrsoft.common.result.Response
     * @Description: 下拉选择得列表
     */
    @GetMapping("/db/db-list")
    @ApiOperation("下拉选择得列表")
    public Response<List<VisualDbSelectListVo>> dblist() {
        QueryWrapper<XjrVisualDb> query = new QueryWrapper<>();
        query.select(XjrVisualDb.class, x -> VoToColumn.Convert(VisualDbSelectListVo.class).contains(x.getColumn()));
        List<XjrVisualDb> list = visualDbService.list(query);
        List<VisualDbSelectListVo> vo = BeanUtil.copyList(list, VisualDbSelectListVo.class);
        return Response.ok(vo);
    }


    /**
     * @Author: 湘北智造-框架开发组
     * @Date: 2021/12/15
     * @Param: id
     * @return: com.xjrsoft.common.result.Response
     * @Description: 下拉选择得列表
     */
    @PostMapping("/db/dynamic-query")
    @ApiOperation("数据源获取数据")
    public Response<List<Map<String,Object>>> dynamicQuery(@RequestHeader("ModuleId") String cryptoString) throws Exception {


        String params = AesUtil.decryptFormBase64ToString(cryptoString, "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm");

        ObjectMapper obj = new ObjectMapper();
        DynamicQueryDto dynamicQueryDto = obj.readValue(params, DynamicQueryDto.class);

        return Response.ok(visualDbService.dynamicQuery(dynamicQueryDto));
    }


}
